package com.example.chengyu.testmvvm.recyclerTest;

import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.chengyu.testmvvm.R;
import com.example.chengyu.testmvvm.databinding.ItemRecyclerBinding;

import java.util.List;

/**
 * Created by 52957 on 2018/4/25.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    public static final String TAG = MyAdapter.class.getSimpleName();

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    private OnItemClickListener onItemClickListener;
    private List<Bean> beanList;

    public MyAdapter(List<Bean> list) {
        this.beanList = list;
    }

    public interface OnItemClickListener {
        void onItemClick(final int id, final Bean bean);
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ItemRecyclerBinding itemRecyclerBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_recycler,parent,false);
        return new MyViewHolder(itemRecyclerBinding);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.itemRecyclerBinding.setNews(beanList.get(position));
        holder.itemRecyclerBinding.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: item" + position);
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position, beanList.get(position));
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return beanList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{
        private final ItemRecyclerBinding itemRecyclerBinding;
        public MyViewHolder(final ItemRecyclerBinding binding) {
            super(binding.getRoot());
            this.itemRecyclerBinding = binding;
        }
    }
}
